package com.hsource.paymentcenter.conf.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author yangYang
 * @version 1.0
 * @date 2020/10/12 13:41
 * @describe
 */
public class PubSubTable {

    //Map的key为主题，Set里面的元素为队列里面的消费者的队列key，该队列用来检测消息是否被正确接受
    private Map<String, Set<String>> pubSubMap = new HashMap();

    @Autowired
    private StringRedisTemplate redisTemplate;
    //添加关系
    public Boolean addComsumer(String topic, String comsumer) {
        Set<String> comsumerList = pubSubMap.get(topic);

        if (comsumerList == null) {
            comsumerList = new HashSet<>();
        }
        Boolean b = comsumerList.add(comsumer);
        pubSubMap.put(topic, comsumerList);
        return b;
    }
    //删除关系
    public Boolean removeComsumer(String topic, String comsumer) {
        Set<String> comsumerList = pubSubMap.get(topic);
        Boolean b =false;
        if(comsumerList!=null){
            b= comsumerList.remove(comsumer);
            pubSubMap.put(topic, comsumerList);
        }
        return b;
    }


    //广播消息
    public void boradCast(String topic, String messageId) {
        //设置监听键
        redisTemplate.opsForValue().set(topic + "_OrderNotifyTerminalManager_" + messageId, messageId);
        //为该队列传入消息id，为后面校验使用
        redisTemplate.opsForList().leftPush(topic+"_OrderNotifyTerminalManager", topic + "_" + messageId);

    }

}
